import ServerDevice from "../ServerDevice";
import {TopicFactory} from "../TopicFactory";

export default class AppDevice {

  constructor(){
    this.topicFactory = new TopicFactory();
    this.topicFactory.init();
  }

  getClientid(username, password) {
    if (!username || !password) {
      return undefined;
    }

    try {
      // MQTT密码
      let timestamp = Date.now().toString();

      // MQTT ClientId
      let clientid =
          "user." + username + "|" + "timestamp=" + timestamp + ",clientType=user" +
          ",securemode=2,signmethod=hmacsha256";
      clientid += "|";
      return clientid;
    } catch (e) {
      console.error(e);
    }
    return undefined;
  }


  init = (deviceBasicData) => {
    this.mqttDevice = new ServerDevice(this.serverDataListener, deviceBasicData, {});
  }

  connectServer = () =>{
    this.mqttDevice.connectServer();
  }

  close() {
    this.mqttDevice.close();
  }

  ping = () =>{
    this.mqttDevice.ping();
  }

  subscribe = (pk, device) => {
    let map = {
      "${productKey}": pk,
      "${deviceName}": device
    };

    let topics = [];
    topics.push(this.topicFactory.getTopic("PropertyPost", "PUSH", map));
    topics.push(this.topicFactory.getTopic("PropertySet", "PUSH", map));
    topics.push(this.topicFactory.getTopic("EventPost", "PUSH", map));
    topics.push(this.topicFactory.getTopic("Service", "PUSH", map));
    topics.push(this.topicFactory.getTopic("OTA_UPGRADE", "PUSH", map, 0));
    topics.push(this.topicFactory.getTopic("OTA_UPGRADE", "PUSH", map, 2));
    topics.push(this.topicFactory.getTopic("OTA_UPGRADE", "PUSH", map, 3));
    let subscribe1 = this.mqttDevice.subscribe(topics);

    console.log("监听topic,", topics);
  }


  serverDataListener = {
    onPushProperty: function (payload) {
      console.log("收到属性推送:", payload.params);
    },
    onPushEvent: function (payload) {
      console.log("收到事件推送:" + payload.params);
    },
    onResSetProperty: function (payload) {
      console.log("收到属性设置回复:" + payload);
    },
    onReService: function (payload) {
      console.log("服务调用回复:" + payload);
    },
    onConnect(sucess){
      console.log("连接服务器:" + sucess);
    },
    onSubAck(sucess){
      console.log("监听topic反馈:" + sucess);
    },
    onPushAck(sucess){
      console.log("push反馈:" + sucess);
    },
    onClose(){
      console.log("连接关闭");
    },
    onOTA(info){
      console.log("升级信息", info);
    }
  };


}
